#include "Comm.hpp"
#include "Log.hpp"

using namespace std;

const int flags = IPC_CREAT | IPC_EXCL;

int main()
{
    CreateFifo();
    int fd = Open(FIFO_FILE, READER);
    assert(fd >= 0);

    key_t key = CreateKey();
    Log() << "key: " << key << '\n';
    Log() << "create share memory begin\n";

    int shmid = shmget(key, MEM_SIZE, flags | 0666);
    if(shmid < 0)
    {
        Log() << "shmget: " << strerror(errno) << '\n';
        return 2;
    }
    Log() << "create shm success: " << shmid << '\n';

    char *str = (char*)shmat(shmid, nullptr, 0);
    Log() << "attach shm : " << shmid << " success\n";

    while(true)
    {
        if(Wait(fd) <= 0)
            break;
        
        printf("%s\n", str);
        sleep(1);
    }

    shmdt(str);
    Log() << "detach shm : " << shmid << " success\n";

    shmctl(shmid, IPC_RMID, nullptr);
    Log() << "delete shm : " << shmid << " success\n";
    Close(fd, FIFO_FILE);

    // key_t key = CreateKey();
    // Log() << "key: " << key << "\n";

    // Log() << "create share memory begin\n";

    // int shmid = shmget(key, MEM_SIZE, flags | 0666);
    // if(shmid < 0)
    // {
    //     Log() << "shmget: " << strerror(errno) << "\n";
    //     return 2;
    // }
    // Log() << "create shm success: " << shmid << '\n';
    // // sleep(5);

    // char *str = (char*)shmat(shmid, nullptr, 0);
    // Log() << "attach shm : " << shmid << " success\n";
    // //sleep(5);

    // while(true)
    // {
    //     printf("%s\n", str);
    //     sleep(1);
    // }

    // shmdt(str);
    // Log() << "detach shm : " << shmid << " success\n";
    // //sleep(5);

    // shmctl(shmid, IPC_RMID, nullptr);
    // Log() << "delete shm : " << shmid << " success\n";
    // //sleep(5);

    return 0;
}